package com.hanhanxiaochong.zhongxiangchuanmei.view.shop.act;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;

import com.hanhanxiaochong.zhongxiangchuanmei.R;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.GoodDetailBean;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.LoginInfoBean;
import com.hanhanxiaochong.zhongxiangchuanmei.presenter.GoodDetailPresenter;
import com.hanhanxiaochong.zhongxiangchuanmei.util.CustomWebViewClient;
import com.hanhanxiaochong.zhongxiangchuanmei.util.GlideImageLoader;
import com.hanhanxiaochong.zhongxiangchuanmei.util.MessageEvent;
import com.hanhanxiaochong.zhongxiangchuanmei.util.ResourcesUtils;
import com.hanhanxiaochong.zhongxiangchuanmei.util.SharedPreferencesUtil;
import com.hanhanxiaochong.zhongxiangchuanmei.util.Utils;
import com.hanhanxiaochong.zhongxiangchuanmei.view.base.BaseActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.view.home.act.ContactUsDialogFragment;
import com.hanhanxiaochong.zhongxiangchuanmei.view.home.act.EvaluationListActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.view.home.act.HomeVipActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.view.iview.IGoodDetailView;
import com.hanhanxiaochong.zhongxiangchuanmei.view.my.act.ShoppingCartActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.widget.StarBar;
import com.hanhanxiaochong.zhongxiangchuanmei.widget.WrapLinearLayout;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.RetrofitSource;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * 商品详情界面
 */
public class GoodDetailActivity extends BaseActivity<GoodDetailPresenter> implements IGoodDetailView {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_share)
    ImageView ivShare;
    @BindView(R.id.iv_shopping_cart)
    ImageView ivShoppingCart;
    @BindView(R.id.good_banner)
    Banner goodBanner;
    @BindView(R.id.tv_price_vip)
    TextView tvPriceVip;
    @BindView(R.id.tv_price_normal)
    TextView tvPriceNormal;
    @BindView(R.id.tv_good_name)
    TextView tvGoodName;
    @BindView(R.id.tv_post_status)
    TextView tvPostStatus;
    @BindView(R.id.good_tag_container)
    WrapLinearLayout goodTagContainer;
    @BindView(R.id.good_star)
    StarBar goodStar;
    @BindView(R.id.tv_good_score)
    TextView tvGoodScore;
    @BindView(R.id.tv_good_evaluation)
    TextView tvGoodEvaluation;
    @BindView(R.id.tv_html_detail)
    WebView tvHtmlDetail;
    @BindView(R.id.iv_become_vip)
    ImageView ivBecomeVip;

    private String good_id;
    private String store_id;
    private String token;
    private String phone;
    private String u_id;

    public static Intent createIntent(Context context, String good_id, String store_id) {
        Intent intent = new Intent(context, GoodDetailActivity.class);
        intent.putExtra("good_id", good_id);
        intent.putExtra("store_id", store_id);
        return intent;
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_good_detail);
        EventBus.getDefault().register(this);
        good_id = getIntent().getStringExtra("good_id");
        store_id = getIntent().getStringExtra("store_id");
        LoginInfoBean loginInfo = SharedPreferencesUtil.getsInstances(this).getLoginInfo();
        token = loginInfo.getToken();
        u_id = loginInfo.getU_id();
    }

    @Override
    protected void initPresenter() {
        mPresenter = new GoodDetailPresenter(this);
    }

    @Override
    protected void init() {
        mPresenter.getGoodDetailInfo(good_id);

        //动态设置轮播图高度(4:3)
        ViewGroup.LayoutParams layoutParams = goodBanner.getLayoutParams();
        layoutParams.height = (int) (Utils.getScreenWidth(mContext) * 0.75);
        goodBanner.requestLayout();
        //设置banner样式
        goodBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        goodBanner.setImageLoader(new GlideImageLoader());
        //设置banner动画效果
        goodBanner.setBannerAnimation(Transformer.Default);
        //设置自动轮播，默认为true
        goodBanner.isAutoPlay(true);
        //设置轮播时间
        goodBanner.setDelayTime(3000);
        //设置指示器位置（当banner模式中有指示器时）
        goodBanner.setIndicatorGravity(BannerConfig.CENTER);
    }

    @OnClick({R.id.iv_back, R.id.iv_shopping_cart, R.id.iv_share, R.id.iv_call,
            R.id.tv_add_shopping_cart, R.id.tv_buy, R.id.iv_become_vip, R.id.tv_good_evaluation})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_shopping_cart:
                startActivity(ShoppingCartActivity.createIntent(this));
                break;
            case R.id.iv_share:
                final String url = "http://gxcm.quan-oo.com/index/users/translate?uid=" + u_id;
                OnekeyShare oks = new OnekeyShare();
                //关闭sso授权
                oks.disableSSOWhenAuthorize();
                // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间等使用
                oks.setTitle(getString(R.string.app_name));
                // titleUrl是标题的网络链接，QQ和QQ空间等使用
                oks.setTitleUrl(url);
                // url仅在微信（包括好友和朋友圈）中使用
                oks.setUrl(url);
                oks.setShareContentCustomizeCallback((platform, paramsToShare) -> {
                    paramsToShare.setText(getString(R.string.app_name));
                    paramsToShare.setText("我分享了一个动态");
                    if (Wechat.NAME.equals(platform.getName())) {
                        paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
                        paramsToShare.setTitleUrl(url);
                        paramsToShare.setTitle(getString(R.string.app_name));
                    } else if (QQ.NAME.equals(platform.getName())) {
                        paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
                        paramsToShare.setTitleUrl(url);
                        paramsToShare.setTitle(getString(R.string.app_name));
                    } else if (SinaWeibo.NAME.equals(platform.getName())) {
                        paramsToShare.setTitleUrl(url);
                        paramsToShare.setTitle(getString(R.string.app_name));
                    }
                });
                // 启动分享GUI
                oks.show(this);
                break;
            case R.id.iv_call:
                if (phone != null) {
                    ContactUsDialogFragment dialogFragment = ContactUsDialogFragment.newInstance(phone);
                    dialogFragment.show(getFragmentManager(), "ContactUsDialogFragment");
                }
                break;
            case R.id.tv_add_shopping_cart:
                mPresenter.addShoppingCart(token, good_id, "1", store_id);
                break;
            case R.id.tv_buy:
                startActivity(PayDetailActivity.createIntent(this, good_id, null, null, null));
                break;
            case R.id.iv_become_vip:
                startActivity(HomeVipActivity.createIntent(this));
                break;
            case R.id.tv_good_evaluation:
                startActivity(EvaluationListActivity.createIntent(this, 1, good_id));
                break;
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    public void setGoodInfo(GoodDetailBean data) {
        phone = data.getTelphone();
        tvPriceVip.setText(String.format(ResourcesUtils.getString(R.string.good_price), data.getPrice_vip()));
        tvPriceNormal.setText(String.format(ResourcesUtils.getString(R.string.good_price), data.getPrice()));
        tvGoodName.setText(data.getName());
        tvPostStatus.setText(data.getTransport());
        goodStar.setStarMark(Float.parseFloat(data.getScore()));
        tvGoodScore.setText(String.format(ResourcesUtils.getString(R.string.good_score), data.getScore()));
        tvGoodEvaluation.setText(String.format(ResourcesUtils.getString(R.string.good_evaluation), data.getSt_num()));


        String[] split = data.getPic().split(",");
        for (int i = 0; i < split.length; i++) {
            split[i] = RetrofitSource.image_url + split[i];
        }
        List<String> pics = Arrays.asList(split);
        goodBanner.setImages(pics).start();

        //富文本信息
        String html = data.getContent();
        tvHtmlDetail.setWebViewClient(new CustomWebViewClient());
        WebSettings webSettings = tvHtmlDetail.getSettings();
        //允许JS执行
        webSettings.setJavaScriptEnabled(true);
        //listview,webview中滚动拖动到顶部或者底部时的阴影
        tvHtmlDetail.setOverScrollMode(View.OVER_SCROLL_NEVER);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); //默认不使用缓存
        webSettings.setDefaultTextEncodingName("utf-8");
        tvHtmlDetail.loadData(html, "text/html; charset=UTF-8", null);//这种写法可以正确解码
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void handleEvent(MessageEvent event){
        if (event.getMessage().equals("pay_success")){
            finish();
        }
    }
}
